import md5 from 'js-md5'
export const message = (content, duration = 1500) => {
  setTimeout(() => {
    return new Promise((resolve) => {
      uni.showToast({
        icon: 'none',
        title: content,
        duration
      })
      setTimeout(() => resolve(''), duration)
    })
  }, 100);

}


// 手机号验证
export const PHONE_TEST = /^1[3|4|5|7|8][0-9]\d{8}$/

// 自定义过滤器
export const filters = text => text || '-'

// 获取OSS路径
export const oss2 = path => (process.env.OSS_IMG + path)

// 获取OSS图片路径
export const ossImg = path => (process.env.OSS_IMG + path)

// DEV_OSS_IMAGE
export const testOssImg = path => (process.env.DEV_OSS_IMG + path)

// 自定义TabBar切换
export const setCurrentTabBar = (index, visible = true) => {
  const curPage = getCurrentPages()[0]
  if (typeof curPage.getTabBar === 'function' && curPage.getTabBar()) {
    curPage.getTabBar().setData({ selected: index, visible })
  }
}

// 获取下载后文件的临时路径
export const getDownloadFileUri = url => {
  return new Promise((resolve) => {
    uni.downloadFile({
      url,
      success: result => {
        result.tempFilePath && resolve(result.tempFilePath)
      }
    })
  })
}

/**
 * @description: 订单状态过滤
 * @param {*} status
 * @returns
 */
export const orderStatusFilter = (status) => {
  let text = ""
  switch (status) {
    case 0:
      text = "待付款"
      break;
    case 1:
      text = "待发货"
      break;
    case 2:
      text = "已发货"
      break;
    case 3:
      text = "已完成"
      break;
    case 4:
      text = "已关闭"
      break;
    case 5:
      text = "无效订单"
      break;
    case 6:
      text = "待付款"
      break;

    default:
      break;

  }
  return text
}

/**
 * @description: 当前时间格式化
 * @param {*} str 输出格式
 * @returns
 */
export const dateTimeStr = (str) => {
  const date = new Date();
  let year = date.getFullYear(); //年
  let month = date.getMonth() + 1; //月
  let day = date.getDate(); //日
  let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //时
  let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //分
  let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
  month >= 1 && month <= 9 ? (month = "0" + month) : "";
  day >= 0 && day <= 9 ? (day = "0" + day) : "";
  hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
  minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
  second >= 0 && second <= 9 ? (second = "0" + second) : "";
  if (str.indexOf('y') != -1) {
    str = str.replace('y', year)
  }
  if (str.indexOf('m') != -1) {
    str = str.replace('m', month)
  }
  if (str.indexOf('d') != -1) {
    str = str.replace('d', day)
  }
  if (str.indexOf('h') != -1) {
    str = str.replace('h', hour)
  }
  if (str.indexOf('i') != -1) {
    str = str.replace('i', minute)
  }
  if (str.indexOf('s') != -1) {
    str = str.replace('s', second)
  }
  return str;

}

/**
 * @description: 解析链接中的参数
 * @param {*} url
 * @param {*} name
 * @returns
 */
export const getQueryString = (url, name) => {
  console.log("url = " + url)
  console.log("name = " + name)
  let reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  let r = url.substr(1).match(reg)
  if (r != null) {
    console.log("r = " + r)
    console.log("r[2] = " + r[2])
    return r[2]
  }
  return null;
}


/**
 * 临时图片路径转base64
 * @param {Object} param 传一个对象，对象里包括
 * url: 临时图片存放路径，选择图片返回的相对路径
 * type: 图片类型，如：png
 */
export const base64 = (url, type) => {
  return new Promise((resolve, reject) => {
    if (!!uni.getFileSystemManager()) {
      uni.getFileSystemManager().readFile({
        filePath: url, //选择图片返回的相对路径
        encoding: "base64", //编码格式
        success: (res) => {
          resolve(
            "data:image/" +
            type.toLocaleLowerCase() +
            ";base64," +
            res.data
          );
        },
        fail: (res) => reject(res.errMsg),
      });
    } else {
      uni.request({
        url: url,
        method: "GET",
        responseType: "arraybuffer",
        success: (ress) => {
          let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
          base64 = "data:image/jpeg;base64," + base64; //不加上这串字符，在页面无法显示的哦
          resolve(base64);
        },
        fail: (res) => reject(res.errMsg),
      });
    }
  });
}



// 拼接加密字符串并加密返回后的签名
export const generateSign = (obj) => {
  // 排序
  function objKeySort(obj) {
    var newkey = Object.keys(obj).sort()
    // 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = {}// 创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) { // 遍历newkey数组
      if (obj[newkey[i]] !== "") {
        newObj[newkey[i]] = obj[newkey[i]]// 向新创建的对象中按照排好的顺序依次增加键值对
      }

    }
    return newObj// 返回排好序的新对象

  }

  obj = objKeySort(obj)

  const paramsJSONStr = JSON.stringify(obj)
  console.log(paramsJSONStr)
  const Str = paramsJSONStr?.replaceAll(':', '=')?.replaceAll(',', '&')?.replaceAll('"', '')?.replace('{', '')?.replace('}', '') + '&IEItqzXp2qwdfpTV'
  return md5(Str)
}

// 拼接加密字符串并加密返回后的签名（熊猫活动外部接口）
export const generateSign2 = (obj) => {
  // 排序
  function objKeySort(obj) {
    var newkey = Object.keys(obj).sort();
    // 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = {}; // 创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) {
      // 遍历newkey数组
      if (obj[newkey[i]] !== "") {
        newObj[newkey[i]] = obj[newkey[i]]; // 向新创建的对象中按照排好的顺序依次增加键值对
      }
    }
    return newObj; // 返回排好序的新对象
  }

  obj = objKeySort(obj);

  const paramsJSONStr = JSON.stringify(obj);
  const Str = paramsJSONStr
    ?.replaceAll(":", "=")
    ?.replaceAll(",", "&")
    ?.replaceAll('"', "")
    ?.replace("{", "")
    ?.replace("}", "");
  return md5(Str + "MRHskAN8OiA8wMiDE3Lfqmh9RCwEDrn5", "UTF-8");
};

// 获取随机数
export const randomString = (params) => {
  let len = len || 32
  const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  const maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd

}

/**
  函数防抖
  fn 目标函数
  wait 延迟执行毫秒数
  immediately true - 立即执行， false - 延迟执行
 */
export const debounce = (fn, wait = 1000, immediately = true) => {
  let timer;
  return function () {
    let that = this,
      args = arguments;
    if (timer) clearTimeout(timer);
    if (immediately) {
      let callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      if (callNow) fn.apply(that, args);
    } else {
      timer = setTimeout(() => {
        fn.apply(that, args);
      }, wait)
    }
  }
}


/**
 函数节流
 fn 函数
 wait 延迟执行毫秒数
 type 1 使用表时间戳，在时间段开始的时候触发 2 使用表定时器，在时间段结束的时候触发
 */
export const throttle = (fn, wait = 1000, type = 1) => {

  let previous = 0;
  let timeout;
  return function () {
    let that = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();
      if (now - previous > wait) {
        fn.apply(that, args);
        previous = now;
        console.log(1111111)
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null;
          fn.apply(that, args)
          console.log(1111111)
        }, wait)
      }
    }
  }
}

/**
 * 对象转换query参数字符串
 * @param obj
 * @returns {string}
 */
export const ObjectToQueryString = (obj) => Object.keys(obj)
  .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
  .join('&');

// no encode
export const ObjectToQueryStringNoEncode = (obj) => Object.keys(obj)
  .map(key => `${key}=${obj[key]}`)
  .join('&');

